#!/usr/bin/env python
# -*- coding: utf8 -*-
def cv(s):
	if type(s)==type(u''): return s
	else: return unicode(s,'utf-8')
class Config:
	def __init__(self):
		self.__dic_data = {}
	def __getitem__(self,att):
		return self.__dic_data[att.lower()]
	def get(self,att,default=None):
		try: return self.__dic_data[att.lower()]
		except: return default
	def __setitem__(self,att,val):
		self.__dic_data[att.lower()] = '%s'%val
	def has_key(self,att):
		return self.__dic_data.has_key(att.lower())
	def __delitem__(self,att):
		try: del self.__dic_data[att.lower()]
		except: pass
	def sections(self):
		ret = []
		for x in self.__dic_data.keys():
			xx = x.split(':',1)[0]
			if xx not in ret: ret.append(xx)
		return ret
	def options(self,opt):
		ret = []
		o = opt.lower()
		for x in self.__dic_data.keys():
			xx = x.split(':',1)
			if xx[0]==o: ret.append(xx[1])
		return ret
	def section(self,sec):
		sl = sec.lower()
		ret = {}
		for x in self.__dic_data.keys():
			xx = x.split(':',1)
			if xx[0] == sl: ret[xx[1]] = self.__dic_data[x]
		return ret
	def open(self,file_name='ms.cnf',clean=False):
		self._file_name = file_name
		if clean: self.__dic_data = {}
		cs = ''
		try:
			for s in open(file_name).xreadlines():
				ss = unicode(s.strip(),'utf-8')
				if len(ss)==0: pass
				elif ss[0] == '#': pass
				elif ss[0] == '[' and ss[-1]==']': cs = ss[1:-1].strip().lower() # Имя секции
				elif cs and ss.find('=')!=-1: # Имя опции и значение
					xx = ss.split('=',1)
					self.__dic_data[u'%s:%s'%(cs,xx[0].strip().lower())] = cv(xx[1].lstrip())
		except: pass
	def set_default(self,default):
		for x,y in default.items():
			self[x] = y
	def save(self):
		sections = self.sections()
		cd = self.__dic_data.copy()
		try: fr = open(self._file_name,'r').readlines()
		except: fr = []
		fw = open(self._file_name,'w')
		cs = ''
		for s in fr:
			ss = s.strip()
			ssx = ss.split(':',1)
			if len(ss)==0: fw.write('\n')
			elif ss[0] == '#': fw.write(cv('%s\n'%ss).encode('utf-8'))
			elif ss[0] == '[' and ss[-1]==']': # Пишем опцию
				sec_name = ss[1:-1].strip().lower()
				if sec_name in sections:
					if cs:
						for x in cd.keys():
							on,os = x.split(u':',1)
							if on==cs:
								fw.write(cv('%s = %s\n'%(os,cd[x])).encode('utf-8'))
								del cd[x]
					fw.write(cv('[%s]\n'%sec_name).encode('utf-8'))
					cs = sec_name
				else: cs = u''
			elif cs and ss.find('=')!=-1: # Имя опции и значение
				xx = ss.split('=',1)
				on = xx[0].strip().lower()
				att = '%s:%s'%(cs,on)
				if cd.has_key(att):
					fw.write(cv('%s = %s\n'%(on,cd[att])).encode('utf-8'))
					del cd[att]
		if cs:
			for x in cd.keys():
				on,os = x.split(':',1)
				if on==cs:
					fw.write(cv('%s = %s\n'%(os,cd[x])).encode('utf-8'))
					del cd[x]
		cs = ''
		cds = cd.keys()
		cds.sort()
		for x in cds:
			xx = x.split(':',1)
			if cs!=xx[0]:
				cs = xx[0]
				print '.'
				fw.write(cv('[%s]\n'%cs).encode('utf-8'))
			fw.write(cv('%s = %s\n'%(xx[1],cd[x])).encode('utf-8'))
		fw.close()
		print '>>> Конфиг файл сохранен.'
